
package com.yuan.unit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.util.DisplayMetrics;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * UI的帮助类
 * 
 * @author YUAN
 */
public class UiUtils {

    private static DisplayMetrics sDisplayMetrics = null;

    public static DisplayMetrics getDisplayMetrics(Activity activity) {
        if (sDisplayMetrics == null) {
            sDisplayMetrics = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(sDisplayMetrics);
        }

        return sDisplayMetrics;
    }

    /**
     * 获取大致相对的时间：今天、昨天、前天、3天以前
     * 
     * @param millseconds
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String getRoughlyRelativeDateString(long milliseconds) {
        long nowDays = System.currentTimeMillis() / 86400000;
        long thisDays = milliseconds / 86400000;

        long daysDivided = nowDays - thisDays;

        if (daysDivided > 3) {
            return "3天之前";
        } else {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            String dayString = null;
            if (daysDivided == 2) {
                dayString = "前天";
            } else if (daysDivided == 1) {
                dayString = "昨天";
            } else if (daysDivided == 0) {
                dayString = "今天";
            }

            dayString += " " + format.format(new Date(milliseconds));

            return dayString;
        }
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     * 
     * @param pxValue
     * @return
     */
    public static int px2dip(Activity activity, float pxValue) {
        return (int) (pxValue / getDisplayMetrics(activity).density + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     * 
     * @param dipValue
     * @param scale（DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Activity activity, float dipValue) {
        return (int) (dipValue * getDisplayMetrics(activity).density + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     * 
     * @param pxValue
     * @return
     */
    public static int px2sp(Activity activity, float pxValue) {
        return (int) (pxValue / getDisplayMetrics(activity).scaledDensity + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     * 
     * @param spValue
     * @return
     */
    public static int sp2px(Activity activity, float spValue) {
        return (int) (spValue * getDisplayMetrics(activity).scaledDensity + 0.5f);
    }

    public static int getFontHeight(float fontSize)
    {
        Paint paint = new Paint();
        paint.setTextSize(fontSize);
        FontMetrics fm = paint.getFontMetrics();
        return (int) (Math.ceil(fm.descent - fm.ascent) + 2);
    }

}
